package com.binhthuan.catechist.server.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.binhthuan.catechist.server.ErrorObject;
import com.binhthuan.catechist.server.ResponseObject;
import com.binhthuan.catechist.server.bus.AreaBUS;
import com.binhthuan.catechist.server.domain.Area;
import com.binhthuan.catechist.shared.constant.Parameter;

public class AreaServlet extends AbstractServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        addArea(request, response);
    }

    @Override
    protected void fetch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter(Parameter.ID) == null) {
            getAllAreas(request, response);
        } else {
            getAreaById(request, response);
        }
    }

    @Override
    protected void remove(HttpServletRequest request, HttpServletResponse response, boolean confirmation) throws ServletException,
            IOException {
        deleteArea(request, response, confirmation);
    }

    @Override
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        updateArea(request, response);
    }

    private void addArea(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter(Parameter.NAME);

        try {
            Area area = new Area();
            area.setName(name);
            
            AreaBUS bus = new AreaBUS();
            if (bus.getAreaByName(name.trim()) != null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().areaIsDuplicated());
                sendResponse(error.toJson());
                return;
            }
            if (bus.save(area)) {
                sendResponse(new ResponseObject(area).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getAllAreas(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            AreaBUS bus = new AreaBUS();
            List<Area> areas = bus.getAllAreas();

            sendResponse(new ResponseObject(areas).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getAreaById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter(Parameter.ID);

        try {
            int areaId = Integer.parseInt(id);

            AreaBUS areaBus = new AreaBUS();
            Area area = areaBus.getAreaById(areaId);

            sendResponse(new ResponseObject(area).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void deleteArea(HttpServletRequest request, HttpServletResponse response, boolean confirmation) throws IOException {
        String areaId = request.getParameter(Parameter.ID);
        try {
            int id = Integer.parseInt(areaId);

            AreaBUS bus = new AreaBUS();
            if (bus.isInUsed(id) && !confirmation) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().itemIsInUsed("\"" + bus.getAreaById(id).getName() + "\""));
                error.setRequireConfirmation(true);
                sendResponse(error.toJson());
                return;
            }

            if (bus.deleteArea(id)) {
                sendResponse(new ResponseObject((Object) null).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void updateArea(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String areaId = request.getParameter(Parameter.ID);
        String name = request.getParameter(Parameter.NAME);

        try {
            int id = Integer.parseInt(areaId);

            AreaBUS bus = new AreaBUS();
            Area currentArea = bus.getAreaByName(name.trim());
            if (currentArea != null && currentArea.getId() != id) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().areaIsDuplicated());
                sendResponse(error.toJson());
                return;
            }

            currentArea = bus.getAreaById(id);
            currentArea.setName(name);

            if (bus.save(currentArea)) {
                sendResponse(new ResponseObject(currentArea).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
